<template>
  <div class="login-container">
    <div class="background-animation">
      <div class="cube"></div>
      <div class="cube"></div>
      <div class="cube"></div>
    </div>
    
    <div class="login-content">
      <div class="title-container">
        <h3 class="title">
          <span class="ai-text">AI</span> Lab管理系统
        </h3>
        <div class="subtitle">智能实验室管理平台</div>
      </div>

      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
        label-position="left">
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input ref="username" v-model="loginForm.username" placeholder="用户名" name="username" type="text"
            tabindex="1" autocomplete="on" />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="大写锁定已开启" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
              placeholder="密码" name="password" tabindex="2" autocomplete="on" @keyup="checkCapslock"
              @blur="capsTooltip = false" @keyup.enter="handleLogin" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-button :loading="loading" type="primary" class="login-button" @click.prevent="handleLogin">
          <span class="button-text">登 录</span>
          <div class="button-glow"></div>
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { validUsername } from '@/utils/validate';
import { defineComponent } from 'vue';
import SocialSign from './components/SocialSignin.vue';
import type { FormItemRule } from 'element-plus';
import type { IForm } from '@/types/element-plus';
import store from '@/store';

interface QueryType {
  // 自定义key 任意字符串
  [propname:string]:string
}

export default defineComponent({
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername: FormItemRule['validator'] = (_rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'));
      } else {
        callback();
      }
    };
    const validatePassword: FormItemRule['validator'] = (_rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {}
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      (this.$refs.username as HTMLElement).focus();
    } else if (this.loginForm.password === '') {
      (this.$refs.password as HTMLElement).focus();
    }
  },
  unmounted() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z');
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        (this.$refs.password as HTMLElement).focus();
      });
    },
    handleLogin() {
      (this.$refs.loginForm as IForm).validate(valid => {
        return new Promise((resolve, reject) => {
          if (valid) {
            this.loading = true;
            store.user().login(this.loginForm)
              .then(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery });
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              }).finally(() => {
                resolve();
              });
          } else {
            console.log('error submit!!');
            reject();
          }
        });
      });
    },
    getOtherQuery(query:QueryType) {
      return Object.keys(query).reduce((acc:QueryType, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       store.user().LoginByThirdparty(codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
});
</script>

<style lang="scss">
$bg: #0a192f;
$light_gray: #fff;
$cursor: #fff;
$primary: #64ffda;
$text: #8892b0;

.login-container {
  position: relative;
  min-height: 100vh;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  
  .background-animation {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
    
    .cube {
      position: absolute;
      width: 100px;
      height: 100px;
      background: rgba(100, 255, 218, 0.1);
      transform-style: preserve-3d;
      animation: float 8s infinite ease-in-out;
      
      &:nth-child(1) {
        top: 20%;
        left: 10%;
        animation-delay: 0s;
      }
      
      &:nth-child(2) {
        top: 60%;
        right: 15%;
        animation-delay: -2s;
      }
      
      &:nth-child(3) {
        bottom: 20%;
        left: 30%;
        animation-delay: -4s;
      }
    }
  }

  .login-content {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }

  .login-form {
    width: 420px;
    padding: 50px 40px;
    background: rgba(10, 25, 47, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(100, 255, 218, 0.1);
    transform: translateY(0);
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 40px rgba(100, 255, 218, 0.15);
    }
  }

  .title-container {
    text-align: center;
    margin-bottom: 50px;

    .title {
      font-size: 36px;
      color: $light_gray;
      margin-bottom: 15px;
      letter-spacing: 1px;
      
      .ai-text {
        color: $primary;
        font-weight: bold;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -5px;
          left: 0;
          width: 100%;
          height: 2px;
          background: $primary;
          transform: scaleX(0);
          transition: transform 0.3s ease;
        }
      }
      
      &:hover .ai-text::after {
        transform: scaleX(1);
      }
    }
    
    .subtitle {
      color: $text;
      font-size: 16px;
      letter-spacing: 0.5px;
    }
  }

  .el-form-item {
    margin-bottom: 30px;
    border: 1px solid rgba(100, 255, 218, 0.1);
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.03);
    transition: all 0.3s ease;
    overflow: hidden;
    display: flex;
    align-items: center;
    padding: 0 15px;

    &:hover {
      border-color: $primary;
      box-shadow: 0 0 15px rgba(100, 255, 218, 0.1);
      transform: translateY(-2px);
    }

    .svg-container {
      padding: 0;
      color: $primary;
      font-size: 18px;
      margin-right: 10px;
      display: flex;
      align-items: center;
    }
  }

  .el-input {
    flex: 1;
    
    .el-input__wrapper {
      background: transparent;
      box-shadow: none;
      padding: 0;
    }

    input {
      color: $light_gray;
      height: 55px;
      font-size: 16px;
      padding: 0;
      letter-spacing: 0.5px;
      
      &::placeholder {
        color: rgba($text, 0.7);
        font-size: 14px;
      }
    }
  }

  .show-pwd {
    position: relative;
    right: 0;
    top: 0;
    transform: none;
    color: $primary;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.3s ease;
    padding: 0 0 0 10px;
    display: flex;
    align-items: center;
    
    &:hover {
      transform: scale(1.1);
    }
  }

  .login-button {
    width: 100%;
    height: 55px;
    background: transparent;
    border: 2px solid $primary;
    color: $primary;
    font-size: 18px;
    font-weight: 500;
    letter-spacing: 2px;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border-radius: 12px;
    margin-top: 10px;
    
    &:hover {
      background: rgba(100, 255, 218, 0.1);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(100, 255, 218, 0.2);
      
      .button-glow {
        transform: translateX(100%);
      }
    }
    
    &:active {
      transform: translateY(0);
    }
    
    .button-text {
      position: relative;
      z-index: 1;
    }
    
    .button-glow {
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(100, 255, 218, 0.2), transparent);
      transition: transform 0.5s ease;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}
</style>
